import json
import os
import tkinter as tk

__all__ = ["PinoutPlanObj","DevicePinoutPlanObj"]

class PinoutPlanObj:
    def __init__(self, Name, PinIsOutsidePackage, NumOfEdageWithLeads, Width, Height, EPExists,EPWidth, EPHeight, Pinsum, FirstedgePinSum, LeadWidth, LeadHeight, LeadPitch,OneMMForPixs, CenterInfo, PinColorEnable,PinInfo,PinTextBackgroundAreaLength,FactorPinNameSizeToPinWidth,LeadNameIsBold):
        self.Name = Name
        self.PinIsOutsidePackage = False if PinIsOutsidePackage.lower() != 'true' else True
        self.Pinsum = int(Pinsum)
        self.FirstedgePinSum = int(FirstedgePinSum)
        if NumOfEdageWithLeads == 4:
            self.SecondedgePinSum = int(self.Pinsum / 2 - self.FirstedgePinSum)  # 修改: 将结果转换为整数
        else:
            self.SecondedgePinSum = 0
        self.OneMMForPixs = int(OneMMForPixs)
        self.CenterInfo = CenterInfo # [{"Text":"","FontSize":0}]
        self.PinInfo = PinInfo
        self.NumOfEdageWithLeads = int(NumOfEdageWithLeads)
        
        self.Width = float(Width) * self.OneMMForPixs
        self.Height = float(Height) * self.OneMMForPixs
        self.EPExists = False if EPExists.lower() != 'true' else True
        self.EPWidth = float(EPWidth) * self.OneMMForPixs
        self.EPHeight = float(EPHeight) * self.OneMMForPixs
        self.LeadWidth = float(LeadWidth) * self.OneMMForPixs
        self.LeadHeight = float(LeadHeight) * self.OneMMForPixs
        self.LeadPitch = float(LeadPitch) * self.OneMMForPixs
        self.PinTextBackgroundAreaLength = float(PinTextBackgroundAreaLength) * self.OneMMForPixs
        self.PinColorEnable = False if PinColorEnable.lower() != 'true' else True
        self.FactorPinNameSizeToPinWidth = float(FactorPinNameSizeToPinWidth)
        self.LeadNameIsBold = False if LeadNameIsBold.lower() != 'true' else True
        
            
        
    def check_valid(self) :
        return True
class DevicePinoutPlanObj:
    def __init__(self, json_path):
        self.json_path = json_path       
        self.plans = DevicePinoutPlanObj.Load(json_path)
        
    def GetPlanNames(self) : 
        names = []
        for plan in self.plans :
            names.append(plan.Name)
        return names
    def GetPlanByName(self,name) : 
        for plan in self.plans :
            if plan.Name == name :
                return plan
        return None
    
    def CheckValid(self) : 
        if self.plans == None :
            return False 
        for plan in self.plans :
            if plan.check_valid() == False :
                return False
        return True
    
    @staticmethod
    def GetDefault(json_path):
        default_config = [{
            "Name": "Demo_QFN",
            "PinIsOutsidePackage": "False",
            "NumOfEdageWithLeads": 4,
            "Width": 0.0,
            "Height": 0.0,
            "EPExists": True,
            "EPWidth": 0.0,
            "EPHeight": 0.0,
            "Pinsum": 48,
            "FirstedgePinSum": 0,
            "PinTextBackgroundAreaLength": 3.0,
            "LeadWidth": 0.0,
            "LeadHeight": 0.0,
            "LeadPitch": 0.0,
            "OneMMForPixs": 0,
            "FactorPinNameSizeToPinWidth": 1.0,
            "LeadNameIsBold": "False",
            "CenterInfo": [{"Text":"Demo","FontSize":30,"IsBold":"true"},{"Text":"substr","FontSize":20,"IsBold":"False"}],
            "PinColorEnable":True,
            "PinInfo":[{"id":1,"text":"VDD","fontcolor":"red","backgroundcolor":"white"},
                       {"id":2,"text":"VDD","fontcolor":"#13f383","backgroundcolor":"yellow"},
                       {"id":0,"text":"VDD","fontcolor":"#e06666","backgroundcolor":"#1c8a64"}]
        }]
        
        with open(json_path, 'w') as f:
            json.dump(default_config, f, indent=4)

    @staticmethod
    def Load(json_path):
        if not os.path.exists(json_path):
            DevicePinoutPlanObj.GetDefault(json_path)
        
        with open(json_path, 'r') as f:
            data = json.load(f)
        
        config_instances = []
        for item in data:
            config_instance = PinoutPlanObj(
                Name=item["Name"],
                PinIsOutsidePackage=item["PinIsOutsidePackage"],
                NumOfEdageWithLeads=item["NumOfEdageWithLeads"],
                Width=item["Width"],
                Height=item["Height"],
                EPExists=item["EPExists"],
                EPWidth=item["EPWidth"],
                EPHeight=item["EPHeight"],
                Pinsum=item["Pinsum"],
                FirstedgePinSum=item["FirstedgePinSum"],
                LeadWidth=item["LeadWidth"],
                LeadHeight=item["LeadHeight"],
                LeadPitch=item["LeadPitch"],
                OneMMForPixs=item["OneMMForPixs"],
                CenterInfo=item["CenterInfo"],
                PinColorEnable=item["PinColorEnable"],
                PinInfo=item["PinInfo"],
                PinTextBackgroundAreaLength=item["PinTextBackgroundAreaLength"],
                FactorPinNameSizeToPinWidth=item["FactorPinNameSizeToPinWidth"],
                LeadNameIsBold=item["LeadNameIsBold"]
            )
            config_instances.append(config_instance)
        return config_instances

# Test process
if __name__ == "__main__":
    test_json_path = "test.json"
    
    # Delete the test.json file if it exists
    if os.path.exists(test_json_path):
        #os.remove(test_json_path)
        pass
    
    # Generate a default JSON file
    #DevicePinoutPlanObj.GetDefault(test_json_path)
    
    # Read the JSON file and get instances
    config_instances = []
    try:
        config_instances = DevicePinoutPlanObj.Load(test_json_path)
        for instance in config_instances:
            print(vars(instance))
    except Exception as e:
        print(e)
    
    inst:DevicePinoutPlanObj = config_instances[0]
    
    
    root = tk.Tk()
    root.title("LeadIDObj Example")
    # Create a canvas
    canvas = tk.Canvas(root, width=1500, height=1500)

    for key, value in inst.PinInfos.items():
        dot_size = 2
        location = value['Location']
        canvas.create_oval(
            200+location[0] - dot_size, 200+location[1] - dot_size,
            200+location[0] + dot_size, 200+location[1] + dot_size,
            fill='red', outline='red'
        )
    
    canvas.pack()
        
    # Run main loop
    root.mainloop()